package com.party.admin.utils;

import com.party.common.constant.Constant;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAdministrator;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.member.IMemberAdministratorService;
import com.party.core.utils.MyBeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.Map;

/**
 * 登陆加密工具类
 * party
 * Created by wei.li
 * on 2016/8/29 0029.
 */
public class RealmUtils {

    public static final String SALT = "tongxing";

    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;

    /**
     * 获取session
     *
     * @return session
     */
    public static Session getSession() {
        try {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession(false);
            if (session == null) {
                session = subject.getSession();
            }
            if (session != null) {
                return session;
            }
        } catch (InvalidSessionException e) {

        }
        return null;
    }


    /**
     * 获取当前登陆用户
     *
     * @return 当前登陆用户
     */
    public static MemberGroup getCurrentUser() {
        Session session = getSession();
        if (null != session) {
            Object currentUser = session.getAttribute(Constant.CURRENT_USER_KEY);
            if (currentUser instanceof Member) {
                Member member = (Member) currentUser;
                MemberGroup memberGroup = new MemberGroup();
                try {
                    MyBeanUtils.copyBeanNotNull2Bean(member, memberGroup);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return memberGroup;
            } else if (currentUser instanceof MemberGroup) {
                return (MemberGroup) currentUser;
            }
        }
        return null;
    }


    /***
     * 用户管理员对应机构 数据查看权限
     * @param params
     * @param memberAdministratorService
     * @return
     */
    public static Map<String, Object> getMemberAdministrator(Map<String, Object> params,
                                                             IMemberAdministratorService memberAdministratorService) {
        MemberGroup currentUser = RealmUtils.getCurrentUser();
        MemberAdministrator byMemberId = memberAdministratorService.getByMemberId(currentUser.getId());
        if (byMemberId == null) {
            params.put("memberId", currentUser.getId());
        }
        return params;
    }

}
